package com.automobile.controller;

import com.automobile.domain.Img;
import com.automobile.service.ImgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.UUID;

/**
 * 类的作用
 *
 * @author liujiamiao
 * @email 2544296058@qq.com
 * @date 2020-05-23 20:51
 */
@RestController
public class FileController {

    @Autowired
    private ImgService imgService;

    @RequestMapping("/upload")
    public String fileUpload(@RequestParam("upload") MultipartFile[] uploads,@RequestParam("id") String id,@RequestParam("status")String status) throws IOException {

        String path= ResourceUtils.getURL("classpath:").getPath()+"static/files/";

        path = URLDecoder.decode(path, "utf-8");

        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        for (MultipartFile upload : uploads) {
            String filename = upload.getOriginalFilename();
            int index = filename.lastIndexOf(".");
            filename = filename.substring(index);
            String uuid = UUID.randomUUID().toString().replace("-", "");
            filename=uuid+"_"+filename;

            System.out.println("status = "+status);

            //保存图片
            if(status.equals("1")){
                System.out.println("1");
                imgService.save(new Img(("files/"+filename),Integer.parseInt(id)));
            }else if(status.equals("2")){
                System.out.println("1");
                Img img = new Img();
                img.setPath("files/"+filename);
                img.setSmartId(Integer.parseInt(id));
                imgService.save2(img);
            }

            upload.transferTo(new File(path,filename));
        }
        return "success";
    }

}
